package com.example.webrtcdemo.webrtc

import android.app.Activity
import android.content.Context
import android.media.AudioManager
import android.os.Handler
import android.os.Looper
import android.util.Log
import org.webrtc.AudioSource
import org.webrtc.AudioTrack
import org.webrtc.Camera2Enumerator
import org.webrtc.CameraVideoCapturer
import org.webrtc.CapturerObserver
import org.webrtc.DataChannel
import org.webrtc.DefaultVideoDecoderFactory
import org.webrtc.DefaultVideoEncoderFactory
import org.webrtc.EglBase
import org.webrtc.IceCandidate
import org.webrtc.MediaConstraints
import org.webrtc.MediaStream
import org.webrtc.PeerConnection
import org.webrtc.PeerConnectionFactory
import org.webrtc.RtpReceiver
import org.webrtc.RtpSender
import org.webrtc.SdpObserver
import org.webrtc.SessionDescription
import org.webrtc.SurfaceTextureHelper
import org.webrtc.SurfaceViewRenderer
import org.webrtc.VideoCapturer
import org.webrtc.VideoFrame
import org.webrtc.VideoSource
import org.webrtc.VideoTrack
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit

/**
 * @作者: smile
 * @时间: 2025/10/9 20:37
 * @描述:
 **/
class WebRtcManager(
    private val context: Context,
    private val signalingClient: SignalingClient,
    private val localVideoView: SurfaceViewRenderer,
    private val remoteVideoView: SurfaceViewRenderer,
    private var remoteUserId: String? = null,
    private val turnConfig: TurnServerConfig? = null
) {
    companion object {
        private const val TAG = "WebRtcManager"
        private const val VIDEO_WIDTH = 1280
        private const val VIDEO_HEIGHT = 720
        private const val VIDEO_FPS = 30
        private const val DATA_CHANNEL_LABEL = "chat"
        private const val STUN_SERVER = "stun:120.79.206.28.121:3478"
      //  private const val STUN_SERVER = "stun:120.24.180.121:3478"
    }

    // WebRTC核心组件
    private lateinit var peerConnectionFactory: PeerConnectionFactory
    private lateinit var peerConnection: PeerConnection
    private lateinit var eglBase: EglBase
    private lateinit var localMediaStream: MediaStream
    private var dataChannel: DataChannel? = null
    private var videoCapturer: VideoCapturer? = null
    private var audioSource: AudioSource? = null

    // 状态管理
    private var isInitialized = false
    private var isDisconnected = false
    private var listener: WebRtcListener? = null
    private var isRenegotiating = false

    // 音频管理
    private val audioManager by lazy {
        context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    }

    // 定时任务
    private val scheduledExecutor = Executors.newSingleThreadScheduledExecutor()
    private var heartbeatFuture: ScheduledFuture<*>? = null
    private var statusCheckFuture: ScheduledFuture<*>? = null
    private var areTracksAdded = false
    private val addedTracks = mutableListOf<RtpSender>()

    init {
        initializeWebRTC()
    }

    private fun initializeWebRTC() {
        Thread {
            try {
// 1. 初始化EGL
                eglBase = EglBase.create()
                Log.d(TAG, "EGL初始化完成")

                // 2. 初始化UI（主线程）
                (context as Activity).runOnUiThread {
                    initSurfaceViews()
                    Log.d(TAG, "SurfaceView初始化完成")
                }

                // 3. 初始化PeerConnectionFactory
                initPeerConnectionFactory()

                // 4. 创建本地媒体流
                localMediaStream = createLocalMediaStream()

                // 5. 创建PeerConnection
                peerConnection = createPeerConnection()

                // 6. 设置信令监听
                setupSignalingListener()

                isInitialized = true
                Log.d(TAG, "WebRTC初始化完成")
                listener?.onInitialized()
            } catch (e: Exception) {
                Log.e(TAG, "WebRTC初始化失败", e)
                listener?.onError("初始化失败: ${e.message}")
            }
        }.start()
    }



    private fun startStatusCheck() {
        statusCheckFuture = scheduledExecutor.scheduleAtFixedRate({
            Log.d(TAG, "定期状态检查:")
            checkWebRTCState()
        }, 1000, 60000, TimeUnit.SECONDS)
    }

    private fun stopStatusCheck() {
        statusCheckFuture?.cancel(false)
        statusCheckFuture = null
    }

    private fun initSurfaceViews() {
        // 初始化视频渲染视图
        localVideoView.init(eglBase.eglBaseContext, null)
        remoteVideoView.init(eglBase.eglBaseContext, null)

        localVideoView.setEnableHardwareScaler(true)
        remoteVideoView.setEnableHardwareScaler(true)

        localVideoView.setMirror(true)
    }

    private fun initPeerConnectionFactory() {
        val options = PeerConnectionFactory.InitializationOptions.builder(context)
            .setEnableInternalTracer(true)
            .setFieldTrials("WebRTC-H264HighProfile/Enabled/") // 添加H264支持
            .createInitializationOptions()
        PeerConnectionFactory.initialize(options)

        // 创建硬件编解码器工厂
        val encoderFactory = DefaultVideoEncoderFactory(
            eglBase.eglBaseContext,
            true,  // 启用硬件编码
            true   // 启用软件回退
        )
        val decoderFactory = DefaultVideoDecoderFactory(eglBase.eglBaseContext)

        peerConnectionFactory = PeerConnectionFactory.builder()
            .setVideoEncoderFactory(encoderFactory)
            .setVideoDecoderFactory(decoderFactory)
            .createPeerConnectionFactory()

        Log.d(TAG, "PeerConnectionFactory初始化完成，支持硬件编解码器")
    }

    private fun createLocalMediaStream(): MediaStream {
        val stream = peerConnectionFactory.createLocalMediaStream("local_stream")

        // 创建音频轨道
        audioSource = peerConnectionFactory.createAudioSource(MediaConstraints())
        val audioTrack = peerConnectionFactory.createAudioTrack("audio_track", audioSource)
        stream.addTrack(audioTrack)

        // 创建视频源和轨道
        val videoSource = createVideoSource()
        val videoTrack = peerConnectionFactory.createVideoTrack("video_track", videoSource)

        // 绑定本地视频渲染
        (context as Activity).runOnUiThread {
            videoTrack.addSink(localVideoView)
        }

        stream.addTrack(videoTrack)

        // 设置音频
        switchToSpeaker(true)

        Log.d(TAG, "本地媒体流创建完成，音频轨道: ${stream.audioTracks.size}, 视频轨道: ${stream.videoTracks.size}")
        return stream
    }

    private fun createVideoSource(): VideoSource {
        val videoSource = peerConnectionFactory.createVideoSource(false)

        // 初始化摄像头
        val videoCapturer = createCameraCapturer()
        val surfaceTextureHelper = SurfaceTextureHelper.create("CameraThread", eglBase.eglBaseContext)

        videoCapturer.initialize(surfaceTextureHelper, context, videoSource.capturerObserver)
        videoCapturer.startCapture(VIDEO_WIDTH, VIDEO_HEIGHT, VIDEO_FPS)
        this.videoCapturer = videoCapturer

        Log.d(TAG, "视频源创建完成，摄像头已启动")
        return videoSource
    }

    private fun createCameraCapturer(): CameraVideoCapturer {
        val enumerator = Camera2Enumerator(context)
        val deviceNames = enumerator.deviceNames

        // 优先使用前置摄像头
        for (name in deviceNames) {
            if (enumerator.isFrontFacing(name)) {
                val capturer = enumerator.createCapturer(name, null)
                if (capturer != null) {
                    Log.d(TAG, "使用前置摄像头: $name")
                    return capturer
                }
            }
        }

        // 其次使用后置摄像头
        for (name in deviceNames) {
            if (enumerator.isBackFacing(name)) {
                val capturer = enumerator.createCapturer(name, null)
                if (capturer != null) {
                    Log.d(TAG, "使用后置摄像头: $name")
                    return capturer
                }
            }
        }

        // 使用任意可用摄像头
        for (name in deviceNames) {
            val capturer = enumerator.createCapturer(name, null)
            if (capturer != null) {
                Log.d(TAG, "使用摄像头: $name")
                return capturer
            }
        }

        throw RuntimeException("未找到可用摄像头")
    }

    private fun getOfferConstraints(): MediaConstraints {
        val constraints = MediaConstraints()

        // 强制约束
        constraints.mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))
        constraints.mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"))

        // 视频编解码器约束
        constraints.mandatory.add(MediaConstraints.KeyValuePair("googCpuOveruseDetection", "true"))
        constraints.mandatory.add(MediaConstraints.KeyValuePair("googCpuOveruseEncodeUsage", "true"))

        // 可选约束
        constraints.optional.add(MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"))
        constraints.optional.add(MediaConstraints.KeyValuePair("RtpDataChannels", "true"))

        Log.d(TAG, "Offer约束配置完成")
        return constraints
    }

    private fun getAnswerConstraints(): MediaConstraints {
        val constraints = MediaConstraints()

        constraints.mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))
        constraints.mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"))

        Log.d(TAG, "Answer约束配置完成")
        return constraints
    }

    private fun createPeerConnection(): PeerConnection {
        val iceServers = mutableListOf<PeerConnection.IceServer>().apply {
            // 添加STUN服务器
            add(PeerConnection.IceServer.builder(STUN_SERVER).createIceServer())
            Log.d(TAG, "已添加STUN服务器: $STUN_SERVER")

            // 添加TURN服务器（如果有）
            turnConfig?.let {
                val turnServer = PeerConnection.IceServer.builder(it.turnUrl)
                    .setUsername(it.username)
                    .setPassword(it.password)
                    .createIceServer()
                add(turnServer)
                Log.d(TAG, "已添加TURN服务器: ${it.turnUrl}")
            }
        }

        val rtcConfig = PeerConnection.RTCConfiguration(iceServers).apply {
            tcpCandidatePolicy = PeerConnection.TcpCandidatePolicy.DISABLED
            bundlePolicy = PeerConnection.BundlePolicy.MAXBUNDLE
            rtcpMuxPolicy = PeerConnection.RtcpMuxPolicy.REQUIRE
            continualGatheringPolicy = PeerConnection.ContinualGatheringPolicy.GATHER_CONTINUALLY
            keyType = PeerConnection.KeyType.ECDSA
            enableDscp = true

            // 添加更多配置选项
            sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN
        }

        val constraints = MediaConstraints().apply {
            mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"))
            mandatory.add(MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"))
        }

        return peerConnectionFactory.createPeerConnection(rtcConfig, constraints, object : PeerConnection.Observer {
            override fun onSignalingChange(state: PeerConnection.SignalingState) {
                Log.d(TAG, "信令状态: $state")
                listener?.onSignalingStateChange(state)
            }

            override fun onIceConnectionChange(state: PeerConnection.IceConnectionState) {
                Log.d(TAG, "ICE连接状态: $state")
                listener?.onConnectionStateChange(state)

                when (state) {
                    PeerConnection.IceConnectionState.CONNECTED -> {
                        listener?.onConnected()
                        startHeartbeat()
                    }
                    PeerConnection.IceConnectionState.COMPLETED -> listener?.onCompleted()
                    PeerConnection.IceConnectionState.DISCONNECTED,
                    PeerConnection.IceConnectionState.FAILED,
                    PeerConnection.IceConnectionState.CLOSED -> {
                        if (!isDisconnected) {
                            isDisconnected = true
                            listener?.onDisconnected()
                            stopHeartbeat()
                        }
                    }
                    else -> {}
                }
            }

            override fun onIceGatheringChange(state: PeerConnection.IceGatheringState) {
                Log.d(TAG, "ICE收集状态: $state")
                listener?.onIceGatheringStateChange(state)
            }

            override fun onIceCandidate(candidate: IceCandidate) {
                Log.d(TAG, "生成ICE候选: ${candidate.sdpMid}")
                remoteUserId?.let {
                    signalingClient.sendIceCandidate(candidate, it)
                }
            }

            override fun onAddStream(stream: MediaStream) {
                Log.d(TAG, "收到远程流，视频轨道数量: ${stream.videoTracks.size}")
                (context as Activity).runOnUiThread {
                    stream.videoTracks.firstOrNull()?.addSink(remoteVideoView)
                    listener?.onRemoteStreamAdded(stream)
                }
            }

            override fun onDataChannel(channel: DataChannel) {
                Log.d(TAG, "收到数据通道: ${channel.label()}")
                dataChannel = channel
                setupDataChannel()
            }

            override fun onIceConnectionReceivingChange(receiving: Boolean) {
                Log.d(TAG, "ICE连接接收状态: $receiving")
            }

            override fun onIceCandidatesRemoved(candidates: Array<out IceCandidate>) {
                Log.d(TAG, "ICE候选被移除: ${candidates.size}")
            }

            override fun onRemoveStream(stream: MediaStream) {
                Log.d(TAG, "远程流被移除")
                listener?.onRemoteStreamRemoved(stream)
            }

            override fun onRenegotiationNeeded() {
                Log.d(TAG, "需要重新协商")
                // 防止重复触发
                if (isRenegotiating) {
                    Log.d(TAG, "已经在重新协商中，忽略此次回调")
                    return
                }

                isRenegotiating = true
                listener?.onRenegotiationNeeded()

                // 3秒后重置重协商状态
                Handler(Looper.getMainLooper()).postDelayed({
                    isRenegotiating = false
                    Log.d(TAG, "重协商状态已重置")
                }, 3000)
            }

            override fun onAddTrack(receiver: RtpReceiver?, mediaStreams: Array<out MediaStream?>) {
                Log.d(TAG, "收到轨道")
                receiver?.track()?.let { track ->
                    when (track) {
                        is VideoTrack -> {
                            Log.d(TAG, "收到远程视频轨道")
                            (context as Activity).runOnUiThread {
                                track.addSink(remoteVideoView)
                            }
                            listener?.onRemoteVideoTrackAdded(track)
                        }
                        is AudioTrack -> {
                            Log.d(TAG, "收到远程音频轨道")
                            listener?.onRemoteAudioTrackAdded(track)
                        }
                    }
                }
            }
        }) ?: throw RuntimeException("创建PeerConnection失败")
    }

    private fun setupDataChannel() {
        dataChannel?.registerObserver(object : DataChannel.Observer {
            override fun onBufferedAmountChange(amount: Long) {
                Log.d(TAG, "数据通道缓冲数量: $amount")
            }

            override fun onStateChange() {
                val state = dataChannel?.state()
                Log.d(TAG, "数据通道状态: $state")

                if (state == DataChannel.State.OPEN) {
                    listener?.onDataChannelConnected()
                }
            }

            override fun onMessage(buffer: DataChannel.Buffer?) {
                buffer?.let {
                    val bytes = ByteArray(it.data.remaining())
                    it.data.get(bytes)
                    val message = String(bytes, StandardCharsets.UTF_8)
                    Log.d(TAG, "收到数据通道消息: $message")
                    listener?.onMessageReceived(message)
                }
            }
        })
    }

    private fun setupSignalingListener() {
        signalingClient.setSignalingListener(object : SignalingClient.SignalingListener {
            override fun onSignalingConnected() {
                Log.d(TAG, "信令服务器连接成功")
                listener?.onSignalingConnected()
            }

            override fun onOfferReceived(offer: SessionDescription, fromUserId: String) {
                Log.d(TAG, "收到OFFER from: $fromUserId")
                remoteUserId = fromUserId

                // 修改SDP以确保兼容性
                val modifiedSdp = modifySdpForVideo(offer.description)
                val modifiedOffer = SessionDescription(offer.type, modifiedSdp)

                peerConnection.setRemoteDescription(object : SimpleSdpObserver() {
                    override fun onSetSuccess() {
                        Log.d(TAG, "远程OFFER SDP设置成功")
                        createAnswer()
                    }

                    override fun onSetFailure(msg: String) {
                        Log.e(TAG, "远程OFFER SDP设置失败: $msg")
                        listener?.onError("设置远程OFFER失败: $msg")
                    }
                }, modifiedOffer)
            }

            override fun onAnswerReceived(answer: SessionDescription, fromUserId: String) {
                Log.d(TAG, "收到ANSWER from: $fromUserId")

                // 修改SDP以确保兼容性
                val modifiedSdp = modifySdpForVideo(answer.description)
                val modifiedAnswer = SessionDescription(answer.type, modifiedSdp)

                peerConnection.setRemoteDescription(object : SimpleSdpObserver() {
                    override fun onSetSuccess() {
                        Log.d(TAG, "远程ANSWER SDP设置成功")
                    }

                    override fun onSetFailure(msg: String) {
                        Log.e(TAG, "远程ANSWER SDP设置失败: $msg")
                        listener?.onError("设置远程ANSWER失败: $msg")
                    }
                }, modifiedAnswer)
            }

            override fun onIceCandidateReceived(candidate: IceCandidate) {
                Log.d(TAG, "收到ICE候选: ${candidate.sdpMid}")
                peerConnection.addIceCandidate(candidate)
            }

            override fun onUserOnline(userId: String) {
                Log.d(TAG, "用户上线: $userId")
            }

            override fun onUserOffline(userId: String) {
                Log.d(TAG, "用户下线: $userId")
            }

            override fun onConnectionError(message: String) {
                Log.e(TAG, "信令连接错误: $message")
                listener?.onError("信令错误: $message")
            }

            override fun onConnectionClosed() {
                Log.d(TAG, "信令连接关闭")
                listener?.onDisconnected()
            }
        })
    }

    fun createAndSendOffer() {
        if (!isInitialized) {
            listener?.onError("WebRTC未初始化")
            return
        }

        if (remoteUserId == null) {
            listener?.onError("远程用户ID未设置")
            return
        }

        Log.d(TAG, "开始创建并发送OFFER to: $remoteUserId")

        // 检查PeerConnection状态
        if (isDisconnected) {
            Log.e(TAG, "PeerConnection已断开，无法创建Offer")
            listener?.onError("连接已断开，请重新初始化")
            return
        }

        // 创建数据通道（如果不存在）
        if (dataChannel == null) {
            val init = DataChannel.Init().apply {
                ordered = true
                maxRetransmitTimeMs = 3000
            }
            dataChannel = peerConnection.createDataChannel(DATA_CHANNEL_LABEL, init)
            setupDataChannel()
            Log.d(TAG, "数据通道已创建")
        }

        // 确保轨道已添加
        addLocalTracksToPeerConnection()

        // 创建OFFER
        val constraints = getOfferConstraints()
        Log.d(TAG, "开始创建Offer...")

        peerConnection.createOffer(object : SimpleSdpObserver() {
            override fun onCreateSuccess(offer: SessionDescription) {
                Log.d(TAG, "原始SDP offer创建成功")

                // 验证原始SDP
                validateAndLogSdp(offer, "原始OFFER")

                // 确保SDP内容不为空
                if (offer.description.isNullOrBlank()) {
                    Log.e(TAG, "SDP内容为空，无法继续")
                    listener?.onError("SDP生成失败：内容为空")
                    return
                }

                try {
                    // 尝试不修改SDP，直接使用原始SDP
                    val finalOffer = if (shouldModifySdp(offer.description)) {
                        Log.d(TAG, "需要修改SDP")
                        val modifiedSdp = modifySdpForVideo(offer.description)
                        SessionDescription(offer.type, modifiedSdp)
                    } else {
                        Log.d(TAG, "使用原始SDP")
                        offer
                    }

                    // 验证最终SDP
                    validateAndLogSdp(finalOffer, "最终OFFER")

                    Log.d(TAG, "开始设置本地SDP...")
                    peerConnection.setLocalDescription(object : SimpleSdpObserver() {
                        override fun onSetSuccess() {
                            Log.d(TAG, "本地SDP设置成功")
                            // 发送SDP
                            signalingClient.sendOffer(finalOffer, remoteUserId!!)
                            Log.d(TAG, "OFFER已发送到信令服务器")
                        }

                        override fun onSetFailure(msg: String) {
                            Log.e(TAG, "本地SDP设置失败: $msg")
                            handleSdpSetFailure(msg, false)
                        }
                    }, finalOffer)

                } catch (e: Exception) {
                    Log.e(TAG, "处理SDP时发生异常", e)
                    listener?.onError("处理SDP失败: ${e.message}")
                }
            }

            override fun onCreateFailure(msg: String) {
                Log.e(TAG, "创建OFFER失败: $msg")
                listener?.onError("创建OFFER失败: $msg")
            }
        }, constraints)
    }

    private fun shouldModifySdp(sdp: String): Boolean {
        // 只在确实缺少视频编解码器时修改
        val hasVideo = sdp.contains("m=video")
        val hasVideoCodecs = sdp.contains("VP8") || sdp.contains("H264") || sdp.contains("96") || sdp.contains("97")

        Log.d(TAG, "SDP检查 - 有视频: $hasVideo, 有视频编解码器: $hasVideoCodecs")

        return hasVideo && !hasVideoCodecs
    }

    /**
     * 使用新的API添加本地音视频轨道到PeerConnection
     */
    private fun addLocalTracksToPeerConnection() {
        try {
            // 如果轨道已经添加，则跳过
            if (areTracksAdded) {
                Log.d(TAG, "轨道已经添加到PeerConnection，跳过重复添加")
                return
            }
            // 获取本地媒体流的轨道
            val audioTracks = localMediaStream.audioTracks
            val videoTracks = localMediaStream.videoTracks

            Log.d(TAG, "本地音频轨道数量: ${audioTracks.size}, 视频轨道数量: ${videoTracks.size}")

            // 添加音频轨道
            audioTracks.forEach { audioTrack ->
                val sender = peerConnection.addTrack(audioTrack, listOf(localMediaStream.id))
                if (sender != null) {
                    addedTracks.add(sender)
                    Log.d(TAG, "音频轨道添加成功")
                } else {
                    Log.e(TAG, "音频轨道添加失败")
                }
            }

            // 添加视频轨道
            videoTracks.forEach { videoTrack ->
                val sender = peerConnection.addTrack(videoTrack, listOf(localMediaStream.id))
                if (sender != null) {
                    addedTracks.add(sender)
                    Log.d(TAG, "视频轨道添加成功")
                } else {
                    Log.e(TAG, "视频轨道添加失败")
                }
            }

            areTracksAdded = true
            Log.d(TAG, "本地轨道已添加到PeerConnection，总发送器数量: ${addedTracks.size}")
        } catch (e: Exception) {
            Log.e(TAG, "添加本地轨道失败", e)
        }
    }

    private fun createAnswer() {
        Log.d(TAG, "开始创建ANSWER")

        peerConnection.createAnswer(object : SimpleSdpObserver() {
            override fun onCreateSuccess(answer: SessionDescription) {
                Log.d(TAG, "Answer创建成功")

                // 修改SDP以确保视频编解码器正确
                val modifiedSdp = modifySdpForVideo(answer.description)
                val modifiedAnswer = SessionDescription(answer.type, modifiedSdp)

                peerConnection.setLocalDescription(object : SimpleSdpObserver() {
                    override fun onSetSuccess() {
                        Log.d(TAG, "本地Answer SDP设置成功")
                        remoteUserId?.let {
                            signalingClient.sendAnswer(modifiedAnswer, it)
                        }
                    }

                    override fun onSetFailure(msg: String) {
                        Log.e(TAG, "本地Answer SDP设置失败: $msg")
                        handleSdpSetFailure(msg)
                    }
                }, modifiedAnswer)
            }

            override fun onCreateFailure(msg: String) {
                Log.e(TAG, "创建Answer失败: $msg")
                listener?.onError("创建Answer失败: $msg")
            }
        }, getAnswerConstraints())
    }

    private fun modifySdpForVideo(originalSdp: String): String {
        if (originalSdp.isBlank()) {
            Log.e(TAG, "原始SDP为空")
            return originalSdp
        }

        try {
            Log.d(TAG, "开始修改SDP，原始长度: ${originalSdp.length}")

            // 先检查原始SDP是否包含视频编解码器
            val hasVideoCodecs = originalSdp.contains("VP8") || originalSdp.contains("H264")
            if (hasVideoCodecs) {
                Log.d(TAG, "原始SDP已包含视频编解码器，无需修改")
                return originalSdp
            }

            // 简单的SDP修改，只确保视频媒体行正确
            val lines = originalSdp.split("\r\n")
            val modifiedSdp = StringBuilder()
            var videoSectionProcessed = false

            for (line in lines) {
                modifiedSdp.append(line).append("\r\n")

                // 处理视频媒体行
                if (line.startsWith("m=video") && !videoSectionProcessed) {
                    // 确保视频媒体行包含正确的payload types
                    if (!line.contains("96") && !line.contains("97") && !line.contains("98")) {
                        Log.d(TAG, "视频媒体行缺少编解码器，添加默认编解码器")
                        // 在视频媒体行后添加编解码器参数
                        modifiedSdp.append("a=rtpmap:96 VP8/90000\r\n")
                        modifiedSdp.append("a=rtcp-fb:96 goog-remb\r\n")
                        modifiedSdp.append("a=rtcp-fb:96 transport-cc\r\n")
                        modifiedSdp.append("a=rtcp-fb:96 ccm fir\r\n")
                        modifiedSdp.append("a=rtcp-fb:96 nack\r\n")
                        modifiedSdp.append("a=rtcp-fb:96 nack pli\r\n")
                        modifiedSdp.append("a=rtpmap:97 H264/90000\r\n")
                        modifiedSdp.append("a=fmtp:97 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f\r\n")
                    }
                    videoSectionProcessed = true
                }
            }

            val result = modifiedSdp.toString()
            Log.d(TAG, "SDP修改完成，新长度: ${result.length}")
            return result
        } catch (e: Exception) {
            Log.e(TAG, "修改SDP时发生异常", e)
            return originalSdp
        }
    }

    private fun validateAndLogSdp(sdp: SessionDescription, stage: String) {
        Log.d(TAG, "SDP验证 [$stage]:")
        Log.d(TAG, "- 类型: ${sdp.type}")
        Log.d(TAG, "- 长度: ${sdp.description.length}")
        Log.d(TAG, "- 内容预览: ${sdp.description.take(500)}...")

        // 检查关键字段
        val hasVideo = sdp.description.contains("m=video")
        val hasAudio = sdp.description.contains("m=audio")
        val hasIce = sdp.description.contains("a=ice-ufrag")

        Log.d(TAG, "- 包含视频: $hasVideo")
        Log.d(TAG, "- 包含音频: $hasAudio")
        Log.d(TAG, "- 包含ICE: $hasIce")

        if (sdp.description.isBlank()) {
            Log.e(TAG, "SDP内容为空!")
        }
    }

    private fun handleSdpSetFailure(error: String,isRetry: Boolean = false) {
        Log.e(TAG, "SDP设置失败处理: $error, 是否为重试: $isRetry")

        // 在错误发生时检查状态
        checkWebRTCState()

        when {
            error.contains("SessionDescription is NULL") -> {
                Log.e(TAG, "SessionDescription为NULL，可能是SDP生成问题")

                if (!isRetry) {
                    listener?.onError("SDP生成失败，正在重新初始化...")

                    // 延迟后重新初始化并重试
                    Handler(Looper.getMainLooper()).postDelayed({
                        Log.d(TAG, "重新初始化并创建OFFER")
                       // reinitializeAndRetryOffer()
                        createOfferWithOriginalSdp()
                    }, 2000)
                } else {
                    listener?.onError("SDP生成失败，请检查网络和权限")
                }
            }
            error.contains("video description recv parameters") -> {
                Log.w(TAG, "视频参数配置错误，尝试重新初始化视频组件")
                listener?.onError("视频配置错误，正在重新初始化...")
                reinitializeVideoComponents()
            }
            error.contains("audio") -> {
                listener?.onError("音频配置错误")
            }
            else -> {
                listener?.onError("SDP设置失败: $error")
            }
        }
    }

    /**
     * 尝试使用原始SDP创建Offer（不修改）
     */
    private fun createOfferWithOriginalSdp() {
        if (remoteUserId == null) return

        val constraints = getOfferConstraints()
        peerConnection.createOffer(object : SimpleSdpObserver() {
            override fun onCreateSuccess(offer: SessionDescription) {
                Log.d(TAG, "原始SDP创建成功，直接使用不修改")
                validateAndLogSdp(offer, "直接使用原始SDP")

                peerConnection.setLocalDescription(object : SimpleSdpObserver() {
                    override fun onSetSuccess() {
                        Log.d(TAG, "原始SDP设置成功")
                        signalingClient.sendOffer(offer, remoteUserId!!)
                    }

                    override fun onSetFailure(msg: String) {
                        Log.e(TAG, "原始SDP设置失败: $msg")
                        listener?.onError("SDP设置失败: $msg")
                    }
                }, offer)
            }

            override fun onCreateFailure(msg: String) {
                Log.e(TAG, "创建原始SDP失败: $msg")
                listener?.onError("无法创建SDP: $msg")
            }
        }, constraints)
    }

    /**
     * 重新初始化并重试创建Offer
     */
    private fun reinitializeAndRetryOffer() {
        Thread {
            try {
                Log.d(TAG, "开始重新初始化并重试Offer...")

                // 1. 移除所有轨道
                removeAllTracks()

                // 2. 重新创建PeerConnection
                peerConnection.close()
                peerConnection = createPeerConnection()
                Log.d(TAG, "PeerConnection重新创建完成")

                // 3. 延迟确保PeerConnection就绪
                Thread.sleep(500)

                // 4. 重新创建Offer
                if (remoteUserId != null) {
                    Handler(Looper.getMainLooper()).post {
                        createAndSendOffer()
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "重新初始化失败", e)
                listener?.onError("重新初始化失败: ${e.message}")
            }
        }.start()
    }

    /**
     * 移除所有已添加的轨道
     */
    private fun removeAllTracks() {
        try {
            addedTracks.forEach { sender ->
                val success = peerConnection.removeTrack(sender)
                Log.d(TAG, "移除轨道发送器: $success")
            }
            addedTracks.clear()
            areTracksAdded = false
            Log.d(TAG, "所有轨道已移除")
        } catch (e: Exception) {
            Log.e(TAG, "移除轨道失败", e)
        }
    }

    private fun reinitializeVideoComponents() {
        Thread {
            try {
                Log.d(TAG, "开始重新初始化视频组件...")

                // 停止当前视频捕获
                videoCapturer?.stopCapture()
                videoCapturer?.dispose()

                // 重新创建视频源和轨道
                val videoSource = createVideoSource()
                val newVideoTrack = peerConnectionFactory.createVideoTrack("video_track_reinit", videoSource)

                // 移除旧的视频轨道并添加新的
                val oldVideoTracks = localMediaStream.videoTracks.toList()
                oldVideoTracks.forEach { track ->
                    localMediaStream.removeTrack(track)
                    track.dispose()
                }

                localMediaStream.addTrack(newVideoTrack)

                // 重新绑定渲染
                (context as Activity).runOnUiThread {
                    newVideoTrack.addSink(localVideoView)
                }

                // 移除旧轨道并重新添加
                removeAllTracks()
                addLocalTracksToPeerConnection()

                Log.d(TAG, "视频组件重新初始化完成")

                // 重新尝试创建Offer
                if (remoteUserId != null) {
                    Log.d(TAG, "重新尝试创建OFFER")
                    createAndSendOffer()
                }
            } catch (e: Exception) {
                Log.e(TAG, "重新初始化视频组件失败", e)
                listener?.onError("视频重新初始化失败: ${e.message}")
            }
        }.start()
    }

    fun checkWebRTCState(): String {
        return buildString {
            append("WebRTC详细状态:\n")
            append("- 初始化: $isInitialized\n")
            append("- 已断开: $isDisconnected\n")
            append("- PeerConnection: ${::peerConnection.isInitialized}\n")
            append("- 远程用户: $remoteUserId\n")
            append("- 数据通道: ${dataChannel?.state()}\n")
            append("- 视频捕获器: ${videoCapturer != null}\n")
            append("- 本地流音频轨道: ${localMediaStream.audioTracks.size}\n")
            append("- 本地流视频轨道: ${localMediaStream.videoTracks.size}\n")
            append("- 轨道已添加: $areTracksAdded\n")
            append("- 发送器数量: ${addedTracks.size}")

            // 检查关键组件状态
            if (::peerConnection.isInitialized) {
                append("\n- PeerConnection信令状态: ${peerConnection.signalingState()}")
                append("\n- PeerConnectionICE状态: ${peerConnection.iceConnectionState()}")
            }
        }.also { Log.d(TAG, it) }
    }

    fun sendP2PMessage(message: String, callback: ((Boolean, String?) -> Unit)? = null) {
        if (dataChannel?.state() != DataChannel.State.OPEN) {
            val errorMsg = "数据通道未连接，当前状态: ${dataChannel?.state()}"
            Log.w(TAG, errorMsg)
            callback?.invoke(false, errorMsg)
            return
        }

        try {
            val buffer = DataChannel.Buffer(
                ByteBuffer.wrap(message.toByteArray(StandardCharsets.UTF_8)),
                false
            )
            val success = dataChannel?.send(buffer) ?: false
            if (success) {
                Log.d(TAG, "P2P消息发送成功: ${message.take(100)}...")
                callback?.invoke(true, null)
            } else {
                val errorMsg = "数据通道发送失败"
                Log.e(TAG, errorMsg)
                callback?.invoke(false, errorMsg)
            }
        } catch (e: Exception) {
            Log.e(TAG, "发送P2P消息异常", e)
            callback?.invoke(false, e.message)
        }
    }

    // 在连接成功后启动状态检查
    private fun startHeartbeat() {
        stopHeartbeat()
        heartbeatFuture = scheduledExecutor.scheduleAtFixedRate({
            if (dataChannel?.state() == DataChannel.State.OPEN) {
                sendP2PMessage("""{"type":"heartbeat","timestamp":${System.currentTimeMillis()}}""")
            }
        }, 500, 30000, TimeUnit.SECONDS)

        // 可选：每60秒检查一次状态
        startStatusCheck()
        Log.d(TAG, "心跳检测已启动")
    }

    private fun stopHeartbeat() {
        heartbeatFuture?.cancel(false)
        heartbeatFuture = null
        Log.d(TAG, "心跳检测已停止")
    }

    fun switchToSpeaker(enable: Boolean) {
        audioManager.mode = AudioManager.MODE_IN_COMMUNICATION
        audioManager.isSpeakerphoneOn = enable
        Log.d(TAG, "扬声器模式: $enable")
    }

    fun setRemoteUserId(userId: String) {
        this.remoteUserId = userId
        Log.d(TAG, "设置远程用户ID: $userId")
    }

    fun setListener(listener: WebRtcListener) {
        this.listener = listener
        Log.d(TAG, "WebRTC监听器已设置")
    }

    fun disconnect() {
        if (isDisconnected) return
        isDisconnected = true

        Log.d(TAG, "开始断开WebRTC连接...")

        stopHeartbeat()
        videoCapturer?.stopCapture()
        videoCapturer?.dispose()
        audioSource?.dispose()
        // 移除所有轨道
        removeAllTracks()
        // 清理本地媒体流
        localMediaStream.audioTracks.forEach { it.dispose() }
        localMediaStream.videoTracks.forEach { it.dispose() }
        stopStatusCheck()
        peerConnection.close()
        scheduledExecutor.shutdown()
        signalingClient.disconnect()

        Log.d(TAG, "WebRTC资源已释放")
    }

    interface WebRtcListener {
        fun onInitialized()
        fun onSignalingConnected()
        fun onConnected()
        fun onCompleted()
        fun onDisconnected()
        fun onDataChannelConnected()
        fun onMessageReceived(message: String)
        fun onConnectionStateChange(state: PeerConnection.IceConnectionState)
        fun onSignalingStateChange(state: PeerConnection.SignalingState)
        fun onIceGatheringStateChange(state: PeerConnection.IceGatheringState)
        fun onRemoteStreamAdded(stream: MediaStream)
        fun onRemoteStreamRemoved(stream: MediaStream)
        fun onRemoteVideoTrackAdded(track: VideoTrack)
        fun onRemoteAudioTrackAdded(track: AudioTrack)
        fun onRenegotiationNeeded()
        fun onError(message: String)
    }

    // 简化的SDP观察者
    private open class SimpleSdpObserver : SdpObserver {
        override fun onCreateSuccess(desc: SessionDescription) {
            Log.d(TAG, "SDP创建成功: ${desc.type}")
        }

        override fun onSetSuccess() {
            Log.d(TAG, "SDP设置成功")
        }

        override fun onCreateFailure(msg: String) {
            Log.e(TAG, "SDP创建失败: $msg")
        }

        override fun onSetFailure(msg: String) {
            Log.e(TAG, "SDP设置失败: $msg")
        }
    }

    /**
     * TURN服务器配置类
     */
    data class TurnServerConfig(
        val turnUrl: String,
        val username: String,
        val password: String
    )
}